package com.atguigu.juc;

import java.util.concurrent.*;

/**
 * @author ：MJS
 * @date ：Created in 2021/4/26  20:24
 * @description：线程池
 */
public class MyThreadPoolDemo {


    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        try{
            //模拟n个顾客来银行办理业务，目前窗口有5个工作人员
            for (int i = 1; i <= 10; i++) {
                int finalI = i;
                threadPoolExecutor.submit(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"给第"+finalI+"名顾客办理业务");
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            threadPoolExecutor.shutdown();
        }
    }

    private static void cachedThreadPool() {
        ExecutorService threadPool = Executors.newCachedThreadPool();//一池n线程，可变的。
        try{
            //模拟20个顾客来银行办理业务，目前窗口有5个工作人员
            for (int i = 1; i <= 20; i++) {
                int finalI = i;
                threadPool.submit(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"给第"+finalI+"名顾客办理业务");
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            threadPool.shutdown();
        }
    }

    private static void singleThreadExecutor() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一线程
        try{
            //模拟20个顾客来银行办理业务，目前窗口有5个工作人员
            for (int i = 1; i <= 20; i++) {
                int finalI = i;
                threadPool.submit(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"给第"+finalI+"名顾客办理业务");
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            threadPool.shutdown();
        }
    }

    private static void fixedThreadPool() {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//固定数量的线程池
        try{
          //模拟20个顾客来银行办理业务，目前窗口有5个工作人员
            for (int i = 1; i <= 20; i++) {
                int finalI = i;
            threadPool.submit(()->{
                System.out.println(Thread.currentThread().getName()+"\t"+"给第"+finalI+"名顾客办理业务");
            });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
          threadPool.shutdown();
        }
    }
}
